package com.zdp.nio.channel.filechannel;

import com.zdp.nio.buffer.BufferMethod;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Channel通道 使用
 */
public class ChannelMethod {
    public static void main(String[] args) throws Exception{
        FileChannel channel = null;
        FileChannel outChannel = null;
        try{
            RandomAccessFile file = new RandomAccessFile("D:\\code\\basic-code\\netty-test\\src\\main\\resources\\File.txt","rw");
            channel = FileChannelMethod.getChannel(file);
            ByteBuffer buffer = ByteBuffer.allocate(1000);
            // 读取
            FileChannelMethod.readData(channel,buffer);
            BufferMethod.writeToRead(buffer);
            BufferMethod.readData(10,buffer);

            String txt = "测试写入数据";
            BufferMethod.readToWrite(buffer);
            BufferMethod.putData(txt.getBytes("utf-8"),buffer);
            RandomAccessFile newFile = new RandomAccessFile("D:\\code\\basic-code\\netty-test\\src\\main\\resources\\NewFile.txt","rw");
            outChannel = FileChannelMethod.getChannel(newFile);
            FileChannelMethod.writeData(outChannel,buffer);
            FileChannelMethod.refreshDict(outChannel);

        }finally {
            channel.close();
            outChannel.close();
        }


    }
}

class FileChannelMethod {

    /**
     * 刷新缓冲区，写入到磁盘中
     * @param channel
     */
    public static void refreshDict(FileChannel channel) throws IOException{
        channel.force(true);
    }

    /**
     * 通道读取数据，写入到 Buffer中 （此时Buffer为写入模式）
     * @param channel 通道
     * @param buffer 缓冲对象
     */
    public static void readData(FileChannel channel, ByteBuffer buffer) throws IOException{
        int length = -1;
        while((length = channel.read(buffer)) != -1){
            // 处理读到buffer中的数据
        }
    }

    /**
     * 将 Buffer中的数据写入到 文件通道中
     * @param channel
     * @param buffer
     * @throws IOException
     */
    public static void writeData(FileChannel channel,ByteBuffer buffer) throws IOException {
        // 切换为 读模式
        buffer.flip();
        int outLength = 0;
        while((outLength = channel.write(buffer))!= 0){
            System.out.println("写入的字节数 :" +outLength);
        }
    }

    public static RandomAccessFile getRandomAccessFile(String fileName) throws IOException{
        URL resource = FileChannelMethod.class.getClassLoader().getResource(fileName);
        RandomAccessFile file = new RandomAccessFile(resource.getFile(),"rw");
        return file;
    }

    /**
     * 获取到文件通道
     * FileChannel 只能通过 FileInputStream/FileOutputStream/RandomAccessFile获取
     * @return
     * @throws IOException
     */
    public static FileChannel getChannel(RandomAccessFile file) throws IOException {
        return file.getChannel();
    }
}
